<template>
<view>
	<view class="d-login">
		<view class="d-b">{{title}}</view>
		<form class="cl">
			<view class="d-a">
				<image src="@/static/images/img/wo2.png"></image>
				<input name="username" placeholder="请输入用户名" v-model="username" id="username"/>
			</view>
			<view class="d-a">
				<image src="@/static/images/img/yz.png"></image>
				<input type="password" name="password" placeholder="请输入密码" v-model="password" id="password"/>
				<!--view class="d-c">发送短信</view-->
			</view>
			<!--view class="d-d">未注册的手机号验证后将自动注册</view-->
			<button form-type="submit" @click="yonghulogin">立即登录</button>

		</form>
		<!--view class="d-f" @click="show = true">登录即同意<text>用户协议</text></view-->
		<view class="d-e cl">
			<!-- #ifdef H5 -->
			<view v-if="isWeixin" class="d-g-2" @click="weixingongzhonghao">
				<image src="@/static/images/img/wx.png"></image>
				<view>微信</view>
			</view>
			<!-- #endif -->
			<!-- #ifdef MP-WEIXIN-->
			<!--showprivacy-->
		    <view v-if="www.xcxdlkg == '开启'" class="d-g-2" @click="jiancelogin">
				<image src="@/static/images/img/wx.png"></image>
				<view>微信</view>
		    </view>
			<!-- #endif -->
		    <view class="d-g-2" @click="D_goRegiste">
		        <image src="@/static/images/img/wo2.png"></image>
		        <view>注册</view>
		    </view>
			<!--view class="d-g" @click="">
			    <image src="@/static/images/img/yz.png"></image>
			    <view>找密码</view>
			</view-->

		</view>
	</view>
	<view class="d-kuan d-xia-10 d-shangxia-100 d-dibu-50" >
		<u-row justify="space-between" gutter="10">
			<u-col span="4" offset="4">
				<u-button type="default" :hairline="true" :plain="true" shape="circle" open-type="getUserInfo" text="返回首页" @click="index"></u-button>
			</u-col>
		</u-row>
	</view>
	<!--u-popup :show="show" @close="close" @open="open">
		<view>
			<text>出淤泥而不染，濯清涟而不妖</text>
		</view>
	</u-popup-->

	<!--u-button @click="show = true">打开</u-button-->
    <uni-popup ref="setinfo" type="dialog" >
        <view style="padding: 12px;width: 260px;border-radius: 11px;background-color: #fff;">
            <view @click="hidepop(false)" style="text-align: center;text-align: right;">
                <text>X</text>
            </view>
            <view style="text-align: center;">
                <text>完善信息</text>
            </view>
            <view>
                <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                    <image class="avatar" :src="avatarUrl" mode="widthFix"></image>
                </button>
            </view>
            <view style="height: 30px;" @touchstart="requirePrivacyAuthorize">
                <input
                    type="nickname"
                    @change="savename"
                    placeholder="设置昵称"
                    :focus="statefocus"
                    v-model="nickname">
            </view>
            <view style="margin-top: 10px;">
                <button @click="hidepop(true)" type="primary">确定</button>
            </view>
        </view>
    </uni-popup>
	<privacy ref="privacy" type="bottom" :refuse="refuse" />

</view>
</template>

<script>


var Api = require("../../utils/api.js");
var util = require("../../utils/util.js");

var wxApi = require("../../utils/wxApi.js");
var wxRequest = require("../../utils/wxRequest.js");
import config from "../../utils/config";
var pageCount = config.getPageCount;
var webSiteName = config.getWebsiteName;
var domain = config.getDomain;
const app = getApp();

export default {
  data() {
    return {
		title: '欢迎登录账号',
		isArticlesList: true,
		listStyle: config.getListStyle,
		shareTitle: config.getWebsiteName,
		pageTitle: '登录',
		articlesList: [],
		postype: "post",
		webSiteName: webSiteName,
		domain: domain,
		username: '',
		password: '',
		cur: 0,
		show: true,
		titles:'标题',
		contents:``,
        defavatarUrl:"",
        avatarUrl:"",
        nickname:"",
        weixinCode:"",
        statefocus:false,
		savenames: '',
		www: [],
		isWeixin:'',
		dangqianUrl:''

    };
  },


  props: {},

    onShow: function () {},
    mounted(){
        this.avatarUrl = this.defavatarUrl
        // this.showpop()
		let _this = this
		if (wx.getPrivacySetting){
		    wx.getPrivacySetting({
		        success: (res) => {
		            console.log(res)
		            if (res.needAuthorization){
		                _this.$refs.privacy.open()
		            }
		
		            // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
		        },
		        fail: () => {},
		        complete:() => {}
		    })
		}
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	  var duixin = this;
	  var dangqianUrl = uni.getStorageSync('dangqianUrl');
	  duixin.dangqianUrl = dangqianUrl;
	// #ifdef H5
		duixin.isWeixin = duixin.isWechat();
		if(duixin.isWeixin){
			duixin.checkWeChatCode(); //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
		}
	// #endif
	//let membercookie = uni.getCookie('member_cookie');
	//let memberuid = uni.getCookie('member_uid');
	//console.log('memberuid',memberuid);
	//console.log('membercookie',membercookie);

	
	//判断用户是否登录
	var userInfo = uni.getStorageSync('userInfo');
	var danqianurls = uni.getStorageSync('danqianurls');
	duixin.danqianurls = danqianurls;
	if (userInfo) {
		duixin.$router.push({ path: '/pages/wo/wo' }) // 跳转到会员页面
	} else {
		//否则跳转到登录页面
		/*uni.navigateTo({
			url: '/pages/login/login'
		});*/
		//this.$router.push({ path: '/pages/login/login' }) // 跳转到登录页面
	}
    var postype = 'post';

    if (options.postype) {
      postype = options.postype;
    }

    //  this.setData({
    //      postype: postype
    //  });
    this.postype = postype;
	this.getWww();

  },
  onReady: function () {
    uni.setNavigationBarTitle({
      title: this.pageTitle
    });
  },
  methods: {
	refuse() {
	    // this.$refs.privacy.open()
	    uni.showToast({
	        icon: 'none',
	        title: '非常抱歉无法为您提供服务，如需服务请先同意相关协议~',
			   duration: 3000
	    });
	    return
	},
      changeFocus(e){
          this.statefocus = e
      },
      requirePrivacyAuthorize(){
          let _this = this
          if (wx.getPrivacySetting) {
              wx.getPrivacySetting({//获取是否需要弹出
                  success: res => {
                      if (res.needAuthorization) {
                          wx.requirePrivacyAuthorize({//该接口请求隐私协议，会自动触发上边的wx.onNeedPrivacyAuthorization
                              success: () => {
                                  _this.statefocus = true
                              },
                              fail: () => {},
                              complete: () => {}
                          })
                      } else {
                          _this.statefocus = true
                      }
                  },
                  fail: () => {},
                  complete: () => {}
              })
          } else {
              _this.statefocus = true
          }
      },
	showpop(){
	  this.$refs.setinfo.open()
	},
	hidepop(n = false){
		console.log("信息",n)
	  if (n){
		  //this.nickname.length <=0 || (this.avatarUrl.length <=0 || this.avatarUrl === this.defavatarUrl)
		  if (this.nickname.length <=0 || (this.avatarUrl.length <=0 || this.avatarUrl === this.defavatarUrl)){
			  uni.showToast({
				  title:'请选择头像 和 名称',
				  icon:"none",
				  duration:3000
			  });
			  return
		  }
		  
		  this.$refs.setinfo.close()
		  this.donelogin()
	  }else{
		  this.$refs.setinfo.close()
	  }
	},
    onChooseAvatar(e) {
		
          //console.log("头像",e)
          //const { avatarUrl } = e.detail.avatarUrl
          this.avatarUrl = e.detail.avatarUrl;
          this.avatarUploadFile(this.avatarUrl)
    },
    avatarUploadFile(e){
          // 上传头像
		  console.log("上传头像",e)
		  this.avatarUrl = e;
    },
    showprivacy(){
       let _this = this
       if (wx.getPrivacySetting){
           wx.getPrivacySetting({
               success: (res) => {
                   console.log(res)
                   if (res.needAuthorization){
                       _this.$refs.privacy.open()
                   }else{
                       _this.xcxWxLogin()
                   }

                   // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
               },
               fail: () => {},
               complete:() => {}
           })
       }else{
           this.xcxWxLogin()
       }
    },
    refuse() {
       // this.$refs.privacy.open()
       uni.showToast({
           icon: 'none',
           title: '非常抱歉无法为您提供服务，如需服务请先同意相关协议~',
		   duration: 3000
       });
	   
       return
    },
	open() {
	  // console.log('open');
	},
	close() {
	  this.show = false
	  // console.log('close');
	},
	index() {
		uni.switchTab({
			url: '/pages/index/index' // 目标页面的路径
		});
	},
	savename(e) {
	  //console.log("用户名",e.detail.value)
	  //const { value } = e.detail.value;
	  this.nickname = e.detail.value;
	  //console.log("用户名nickname",this.nickname)
	},
	//站点信息
	getWww() {
		var self = this;
		self.setData({
		  www: []
		});
		var getTubiaoRequest = wxRequest.getRequest(Api.getWww());
		getTubiaoRequest.then(response => {
			if (response.data.code == 1) {
			  //console.log("站点",response.data.data); 
			  self.www = response.data.data
			} else {
			  self.setData({
				displaySwiper: "none"
			  });
			}
		});
	},
    // 用户名登录
	async yonghulogin() {
		try {
			var duixin = this;
			duixin.setData({
			  data: []
			});
			var name = this.username;
			var password = this.password;
			var datas = "is_ajax=1&data[username]="+name+"&data[password]="+password;
			var postYonghuLoginRequest = wxRequest.postRequest(Api.postYonghuLogin(),datas);
				postYonghuLoginRequest.then(response => {
					if (response.data.code == 1) {
					  //console.log(response.data.data);
					  //im提示
					  
					  	// 创建websocket
						var imname = response.data.data.member.name;
						// id 
						var imid = response.data.data.member.uid;

					  	var login_data = '{"type":"login","name":"'+imname+'","room_id":"1","uid":"'+imid+'"}';
					  	//console.log("登录成功，发送登录数据:"+login_data);
					  	
						/*#ifdef H5*/
						duixin.duixinim.send(login_data);
						/*#endif*/
						/*#ifdef MP-WEIXIN  || APP-PLUS*/
						uni.sendSocketMessage({
						      data: login_data
						});
						/*#endif*/
					
					    // 保存用户信息到本地storage
					    uni.setStorageSync('userInfo', response.data.data.auth);
						uni.setStorageSync('memberuid', response.data.data.member.uid);
						uni.setStorageSync('member', response.data.data.member);
						uni.setStorageSync('keycode', response.data.data.auth);
						//登录跳转到登录页面
						if(duixin.dangqianUrl){
							setTimeout(() => {
								uni.reLaunch({ url: duixin.dangqianUrl });
							}, 1000);
						} else {
							setTimeout(() => {
								uni.reLaunch({ url: "/pages/wo/wo" });
							}, 1000);
						}
						
					} else {

					  uni.showToast({
					  	icon: 'none',
					  	title: response.data.msg,
					  });
					}
				});

			} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '登录失败，请稍后重试'
				});
			}

	},
	//判断用户 完成注册
	async jiancelogin(){
		try {
			var self = this;
			//console.log("到登录了");
			uni.showToast({
				title: "正在登录...",
				icon: 'loading',
				success: function () {
				}
			});
			uni.login({
			    success: function (res) {
					//console.log("到登录了login",res);
					uni.getUserInfo({
						desc: '完善会员资料',
						success: (userRes) => {
							//console.log("到登录了userRes",res);
						    uni.request({
								url: Api.getWwwUrl()+"s=weixin&c=member&m=xcx",
								data: {
									json: userRes.rawData,
									js_code: res.code,
									jianceopenid:1,
								},
								method: 'post',
								header: {
								  'Content-Type': 'application/x-www-form-urlencoded',
								},
								success: function (res) {
								  console.log(res.data);
								    if (res.data.code) {
									  if (res.data.msg == 'login') {
										  uni.setStorageSync('memberuid', res.data.data.member.uid);
										  uni.setStorageSync('userInfo', res.data.data.auth);
										  uni.setStorageSync('member', res.data.data.member);
										  uni.setStorageSync('keycode', res.data.data.auth);
										uni.showToast({
											title: "登录成功",
											icon: 'success',
											success: function () {
											}
										});
										  // 登录成功
										  console.log("登录成功了",res.data.data.member.uid);
										  
					
										// 跳转新页面
										
										if(self.dangqianUrl){
											setTimeout(() => {
												uni.reLaunch({ url: self.dangqianUrl });
											}, 1000);
										} else {
											setTimeout(() => {
												uni.reLaunch({ url: "/pages/wo/wo" });
											}, 1000);
										}

										
					
									  } else {
										  // 绑定账号注册
										  uni.showModal({
											  showCancel: false,
											  content: "后台微信插件中需要开启直接登录模式"
										  })
									  }
									} else if (res.data.msg == 'unoid') {
										self.showprivacy();
								    } else {
									    // 失败了
									    uni.showModal({
										    showCancel: false,
										    content: res.data.msg
									    })
								  }
								}
								});
						}
					})
				}
			});
		} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '登录失败，请稍后重试'
				});
			}
	},
	//完善用户新 完成注册
	async donelogin(){
		try {
			var self = this;
			//console.log("到登录了");
			uni.login({
			    success: function (res) {
					//console.log("到登录了login",res);
					uni.getUserInfo({
						desc: '完善会员资料',
						success: (userRes) => {
							//console.log("到登录了userRes",res);
							console.log("nickname",self.nickname);
							console.log("avatarUrl",self.avatarUrl);
						    uni.request({
								url: Api.getWwwUrl()+"s=weixin&c=member&m=xcx",
								
								data: {
									json: userRes.rawData,
									js_code: res.code,
									nickname: self.nickname,
									avatarUrl: self.avatarUrl,
								},
								method: 'post',
								header: {
								  'Content-Type': 'application/x-www-form-urlencoded',
								},
								success: function (res) {
								  //console.log(res.data);
								    if (res.data.code) {
									  if (res.data.msg == 'login') {
										  uni.setStorageSync('memberuid', res.data.data.member.uid);
										  uni.setStorageSync('userInfo', res.data.data.auth);
										  uni.setStorageSync('member', res.data.data.member);
										  uni.setStorageSync('keycode', res.data.data.auth);
										  self.D_post_uptouxiang(res.data.data.member.id,res.data.data.auth,self.avatarUrl);
										  //console.log("图片",self.avatarUrl);
										uni.showToast({
											title: "登录成功",
											icon: 'success',
											success: function () {
											}
										});
										// 登录成功
										  console.log("登录成功了");
										// 跳转新页面
										if(self.dangqianUrl){
											setTimeout(() => {
												uni.reLaunch({ url: self.dangqianUrl });
											}, 1000);
										} else {
											setTimeout(() => {
												uni.reLaunch({ url: "/pages/wo/wo" });
											}, 1000);
										}
					
									  } else {
										  // 绑定账号注册
										  uni.showModal({
											  showCancel: false,
											  content: "后台微信插件中需要开启直接登录模式"
										  })
									  }
									} else {
									    // 失败了
									    uni.showModal({
										    showCancel: false,
										    content: res.data.msg
									    })
								  }
								}
								});
						}
					})
				}
			});
		} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '登录失败，请稍后重试'
				});
			}
	},
	async xcxWxLogin() {
          let _this = this
		try {
            uni.login({
                provider:'weixin',
			    success: function (res) {
			        if (res.code) {
                        console.log(res);
                        _this.weixinCode = res.code;
                        //这里要掉接口查 通过code 去拿openid，然后插是否绑定了用户，如果绑定了登陆 没有
                        //打开完善信息 进入完善信息流程
                        _this.$refs.setinfo.open()
			        } else {
			            console.log('登录失败：' + res.errMsg)
			        }
			    }
			});
		} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '登录失败，请稍后重试'
				});
			}
	},
	async xcxWxBangding() {
		
		try {
			var duixin = this;
			uni.login({
			    success: function (res) {
			        console.log(res);
			        if (res.code) {
			            uni.getUserInfo({
			                success: function (userRes) {
			                    //发起网络请求D
			                    uni.request({
			                        url: Api.getWeixinBangding(),
			                        data: {
			                            json: userRes.rawData,
			                            js_code: res.code
			                        },
			                        method: 'post',
			                        header: {
			                            'Content-Type': 'application/x-www-form-urlencoded',
			                        },
			                        success: function (res) {
			                            console.log(res.data);
			                            if (res.data.code) {
			                                if (res.data.msg == 'login') {
			                                    // 登录成功
			                                    console.log("登录成功了");
			                                    uni.setStorageSync('memberuid', res.data.data.member.uid);
			                                    uni.setStorageSync('userInfo', res.data.data.auth);
			                                    uni.setStorageSync('member', res.data.data.member);
												uni.setStorageSync('keycode', res.data.data.auth);
			                                    uni.showToast({
			                                        title: "登录成功",
			                                        icon: 'success',
			                                        success: function () {
			                                            // 跳转新页面
			                                            if(duixin.dangqianUrl){
			                                            	setTimeout(() => {
			                                            		uni.reLaunch({ url: duixin.dangqianUrl });
			                                            	}, 1000);
			                                            } else {
			                                            	setTimeout(() => {
			                                            		uni.reLaunch({ url: "/pages/wo/wo" });
			                                            	}, 1000);
			                                            }
			                                        }
			                                    })

			                                } else {
			                                    // 绑定账号注册
			                                    uni.showModal({
			                                        showCancel: false,
			                                        content: "后台微信插件中需要开启直接登录模式"
			                                    })
			                                }
			                            } else {
			                                // 失败了
			                                uni.showModal({
			                                    showCancel: false,
			                                    content: res.data.msg
			                                })
			                            }
			                        }
			                    });


			                }
			            });
			        } else {
			            console.log('登录失败：' + res.errMsg)
			        }
			    }
			});

		} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '登录失败，请稍后重试'
				});
			}
	},
	//微信H5登录
	async weixinh5(){
		try {
			var duixin = this;
			uni.showToast({
				title: "正在登录...",
				icon: 'loading',
				success: function () {
				}
			});
			uni.login({
				provider: 'weixin', //使用微信登录
				"onlyAuthorize": true, // 微信登录仅请求授权认证
			    success: function (res) {
			        console.log('登录cc：' + res.code)
			        if (res.code) {
			            //获取当前页面地址作为回调地址
			            let local = encodeURIComponent(window.location.href);
						//发起网络请求D
						uni.request({
						    url: Api.postWeixinlogin(),
						    data: {
						        code: res.code,
						        state: local
						    },
						    /*method: 'get',
						    header: {
						        'Content-Type': 'application/x-www-form-urlencoded',
						    },*/
						    success: function (res) {
						        console.log(res.data);
						        if (res.data.code) {
						            if (res.data.msg == 'ok') {
						                // 登录成功
						                console.log("登录成功了");
						                uni.setStorageSync('memberuid', res.data.data.member.uid);
						                uni.setStorageSync('userInfo', res.data.data.auth);
						                uni.setStorageSync('member', res.data.data.member);
										uni.setStorageSync('keycode', res.data.data.auth);
						                uni.showToast({
						                    title: "登录成功",
						                    icon: 'success',
						                    success: function () {
						                        // 跳转新页面
						                        if(duixin.dangqianUrl){
						                        	setTimeout(() => {
						                        		uni.reLaunch({ url: duixin.dangqianUrl });
						                        	}, 1000);
						                        } else {
						                        	setTimeout(() => {
						                        		uni.reLaunch({ url: "/pages/wo/wo" });
						                        	}, 1000);
						                        }
						                    }
						                })
						
						            } else {
						                // 绑定账号注册
						                uni.showModal({
						                    showCancel: false,
						                    content: "后台微信插件中需要开启直接登录模式"
						                })
						            }
						        } else {
						            // 失败了
						            uni.showModal({
						                showCancel: false,
						                content: res.data.msg
						            })
						        }
						    }
						});
			        } else {
			            console.log('登录失败：' + res.errMsg)
			        }
			    }
			});
			
			/*uni.login({
			    success: function (res) {
					//console.log("到登录了login",res);
					
				}
			});*/
		} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '登录失败，请稍后重试'
				});
			}
	},
	D_goRegiste() {
		uni.navigateTo({
			url: '/pages/login/registe' // 目标页面的路径
		});
	},
	//上传头像
	D_post_uptouxiang(uid,code,img) {
		uni.uploadFile({
		  url: Api.postTouxiang(uid,code), //仅为示例，非真实的接口地址
		  filePath: img,
		  name: 'file',
		  formData: {
		    is_ajax:1
		  },
		header: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		  success (res){
		    //const data = res.data
		    //do something
			
		  }
		})
	},
	// #ifdef H5
	//方法：用来判断是否是微信内置的浏览器
	isWechat() {
		return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
	},
	// #endif
	//方法:用来提取code
	getUrlCode(name) {
		return (decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null)
	},
	//检查浏览器地址栏中微信接口返回的code
	checkWeChatCode() {
		let code = this.getUrlCode("code");
		console.log("code",code);
		/*uni.showToast({
			title:`微信code=${code}`
		})*/
		if (code) {
			this.getOpenidAndUserinfo(code)
		}
	},
	//把code传递给后台接口，静默登录
	getOpenidAndUserinfo(code) {
		//获取当前页面地址作为回调地址
		var duixin = this;
		let local = '/pages/wo/wo';
		var url = Api.postWeixinlogin(code,local);
		//window.location.href = url;
		//console.log('posturl',url); 
		//console.log('code',code); 
		
		var postWeixinloginRequest = wxRequest.getRequest(Api.postWeixinlogin(code,local));
		//console.log('postWeixinloginRequest',postWeixinloginRequest); 
		postWeixinloginRequest.then(response => {
			if (response.data.code == 1) {
			  //console.log(response.data.data); 
			  uni.setStorageSync('memberuid', response.data.data.member.uid);
			  uni.setStorageSync('userInfo', response.data.data.auth);
			  uni.setStorageSync('member', response.data.data.member);
			  uni.setStorageSync('keycode', response.data.data.auth);
			  uni.showToast({
			      title: "登录成功",
			      icon: 'success',
			      success: function () {
			          // 跳转新页面
			          if(duixin.dangqianUrl){
			          	setTimeout(() => {
			          		uni.reLaunch({ url: duixin.dangqianUrl });
			          	}, 1000);
			          } else {
			          	setTimeout(() => {
			          		uni.reLaunch({ url: "/pages/wo/wo" });
			          	}, 1000);
			          }
			      }
			  })
			} else {
			  console.log('postWeixinloginRequest',登录失败); 
			}
		});
		
	},
	//微信公众号登录接口
	weixingongzhonghao(){
		var duixin = this;
		//获取当前页面地址作为回调地址
		let local = encodeURIComponent(window.location.href);
		//微信公众号登录接口
		var wenxinurl = Api.postWeixingongzhonghaologin(local);
		//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
		window.location.href = wenxinurl;
		//console.log("到登录了login",location.href);
		
	}
  }
};
</script>
<style lang="scss">
@import "./login.css";
page {
	background-color: #f3f4f7;
}
.avatar-wrapper {
    padding: 0;
    width: 56px!important;
    border-radius: 25px;
    margin-top: 20px;
    margin-bottom: 10px;
}

.avatar {
    display: block;
    width: 56px;
    height: 56px;
}

</style>
